﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using Consult;
using Worker.Properties;


namespace Worker
{
    public partial class Form1 : Form
    {
        private ConsultWorker _worker;
        private const string TypeOfParserEnumString = "TypeOfParser_Enum_";
        //private Thread thread;

        public Form1()
        {
            InitializeComponent();
            InitParsers();
            LoadSettings();
            StartWork(false);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (pnlSettings.Enabled)
            {
                StoreSettings();

                if (_worker == null)
                    _worker = new ConsultWorker();
                else
                    _worker.Terminate();

                _worker.NeedCapthaRecognize += worker_NeedCapthaRecognize;
                _worker.SomeMessage += worker_SomeMessage;
                _worker.SomeLog += worker_SomeLog;
                _worker.CountryName = tbCountry.Text;
                _worker.CityName = tbCity.Text;
                _worker.TypeName = tbType.Text;
                _worker.OfficeName = tbOffice.Text;
                _worker.TypeOfParser = TypeOfParser;
                StartWork(true);
                //thread = new Thread(worker.RunThread);
                //thread.Start();
                _worker.RunThread();
            }
            else
            {
                _worker.Terminate();
                _worker.Dispose();
                _worker = null;
                StartWork(false);
            }
        }

        private TypeOfParser TypeOfParser
        {
            get { return (TypeOfParser)tbParserType.SelectedValue; }
            set { tbParserType.SelectedValue = value; }
        }

        private void InitParsers()
        {
            tbParserType.DataSource = Enum.GetValues(typeof(TypeOfParser)).Cast<TypeOfParser>().Where(i => i != TypeOfParser.Karta).Select(v => new
                                                                                            {
                                                                                                Value = v,
                                                                                                Text = Resources.ResourceManager.GetObject(TypeOfParserEnumString + v)
                                                                                            }).ToArray();
        }

        void worker_SomeLog(object sender, MessageEventArgs e)
        {
            tbLog.AppendText(string.Format("[{0:HH:mm:ss}]: {1}{2}", DateTime.Now, e.Message, Environment.NewLine));
        }

        private void StartWork(bool isStart)
        {
            pnlLog.Left = pnlSettings.Left;
            pnlLog.Top = pnlSettings.Top;
            pnlLog.Width = pnlSettings.Width;
            pnlLog.Height = pnlSettings.Height;
            pnlSettings.Visible = !isStart;
            tbLog.Text = string.Empty;
            pnlLog.Visible = isStart;
            button1.Text = isStart ? Resources.Form1_StartWork_Stop_working : Resources.Form1_StartWork_Start_working;
        }

        void worker_SomeMessage(object sender, MessageEventArgs e)
        {
            MessageBox.Show(e.Message);
            e.IsTerminate = true;
            //worker.Terminate();
            //worker.Dispose();
            _worker = null;
            //if (thread.IsAlive)
            //thread.Abort();
            //thread = null;
            StartWork(false);
        }

        void worker_NeedCapthaRecognize(object sender, CaptchaEventArgs e)
        {
            using (var cf = new CaptchaForm { CaptchaImage = e.Image })
            {
                cf.ShowDialog();
                e.Result = cf.CaptchaAnswer;
            }
        }

        private void StoreSettings()
        {
            ApplicationSettings.Instance.CountryName = tbCountry.Text;
            ApplicationSettings.Instance.CityName = tbCity.Text;
            ApplicationSettings.Instance.TypeName = tbType.Text;
            ApplicationSettings.Instance.OfficeName = tbOffice.Text;
            ApplicationSettings.Instance.Timeout = trackBar1.Value;
            ApplicationSettings.Instance.TypeOfParser = TypeOfParser;
            ApplicationSettings.Instance.PrevCountries =
                tbCountry.Items.Cast<string>().Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
            ApplicationSettings.Instance.PrevCities = tbCity.Items.Cast<string>().Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
            ApplicationSettings.Instance.PrevTypes = tbType.Items.Cast<string>().Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
            ApplicationSettings.Instance.PrevOffices = tbOffice.Items.Cast<string>().Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
            ApplicationSettings.Serialize();
        }

        private void LoadSettings()
        {
            ApplicationSettings.Deserialize();
            InitCombo(tbCountry, ApplicationSettings.Instance.CountryName, ApplicationSettings.Instance.PrevCountries);
            InitCombo(tbCity, ApplicationSettings.Instance.CityName, ApplicationSettings.Instance.PrevCities);
            InitCombo(tbType, ApplicationSettings.Instance.TypeName, ApplicationSettings.Instance.PrevTypes);
            InitCombo(tbOffice, ApplicationSettings.Instance.OfficeName, ApplicationSettings.Instance.PrevOffices);
            TypeOfParser = ApplicationSettings.Instance.TypeOfParser;
            trackBar1.Value = ApplicationSettings.Instance.Timeout;
        }

        private void InitCombo(ComboBox combo, string value, string[] values)
        {
            combo.Items.Clear();
            if (values != null)
                combo.Items.AddRange(values);
            combo.Text = value;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_worker != null)
                _worker.Dispose();
            StoreSettings();
            Process.GetCurrentProcess().Kill();
            Application.Exit();
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            lbTime.Text = trackBar1.Value + " " + Resources.Form1_trackBar1_Scroll_s;
        }

        private void tbCombo_Leave(object sender, EventArgs e)
        {
            var combo = sender as ComboBox;
            if (combo == null)
                return;
            if (combo.Items.Cast<object>().All(item => item.ToString().Trim().ToUpper() != combo.Text.Trim().ToUpper()))
                combo.Items.Add(combo.Text);
        }

        private void tbLog_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
